package com.neo.tiny.middle.socket.websocket.util;

import cn.hutool.core.lang.Assert;
import com.neo.tiny.middle.socket.dto.IotWebsocketClientInfo;
import lombok.experimental.UtilityClass;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: WebSocket工具类
 * @Author: yqz
 * @CreateDate: 2023/1/15 20:28
 */
@UtilityClass
public class IotWebSocketMsgSender {

    /**
     * 客户端clientId为key
     */
    public static final ConcurrentHashMap<String, IotWebsocketClientInfo> IOT_CLIENT_MAP = new ConcurrentHashMap<>(256);

    public void addClient(String clientId, Session session) {
        IotWebsocketClientInfo clientInfo = new IotWebsocketClientInfo();
        clientInfo.setClientId(clientId);
        clientInfo.setSession(session);
        IOT_CLIENT_MAP.put(clientId, clientInfo);
    }

    public void removeClient(String clientId) {

        IOT_CLIENT_MAP.remove(clientId);
    }

    /**
     * 根据客户端id获取客户端会话
     *
     * @param clientId 客户端id
     * @return 会话
     */
    public IotWebsocketClientInfo getClientById(String clientId) {

        return IOT_CLIENT_MAP.get(clientId);
    }

    /**
     * 给指定客户端发消息
     *
     * @param clientId 客户端id
     * @param content  内容
     */
    public IotWebsocketClientInfo sendMsg(String clientId, String content) {
        IotWebsocketClientInfo clientInfo = getClientById(clientId);

        Session session = clientInfo.getSession();
        Assert.notNull(session, "该客户端不在线");
        try {
            session.getBasicRemote().sendText(content);
            // 发送ping
            //PingMessage pingMessage = new PingMessage();
            //session.getBasicRemote().sendPing(pingMessage.getPayload());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return clientInfo;
    }

    /**
     * 获取所有的websocket客户端
     *
     * @return 客户端集合
     */
    public Map<String, IotWebsocketClientInfo> listAllWebSocketClient() {
        return IOT_CLIENT_MAP;
    }

    /**
     * 改变客户端开关状态
     *
     * @param clientId     客户端id
     * @param switchStatus 状态
     */
    public void changeIotClientStatus(String clientId, String switchStatus) {
        IotWebsocketClientInfo clientInfo = getClientById(clientId);
        if (Objects.nonNull(clientInfo)) {
            clientInfo.setSwitchStatus(switchStatus);
        }
    }
}
